

package com.simplebible.util;

import java.util.Scanner;
import java.util.regex.Pattern;
import com.simplebible.bible.objects.Abreviation;

/**
 *
 * @author Williams Lopez
 */
public class HumanVerseParser {
    
    /*
	Abrv ->   Book
                 |Book Chapter
                 |Book Chapter : Verse
	
	Book ->   Number SimpleName
                 |SimpleName
    
        SimpleName -> Palabra Palabra
                      Palabra
				 
	Chapter -> [0-9]+
	Verse   -> [0-9]+
	Number  -> [0-9]+
	Palabra -> [a-zA-Z][a-zA-Z0-9.]*
	Espacio -> [ ]+
	
    */
    
    private static final Pattern numberPattern   = Pattern.compile("[0-9]+");
    private static final Pattern wordPattern   = Pattern.compile("[a-zA-ZáéíóúÁÉÍÓÚ][a-zA-Z0-9.]*");
    private static final Pattern dot2Pattern   = Pattern.compile("[: \t\n\r\b]");
    
    
    public static Abreviation parse(String text) throws Exception{
        Scanner scn = new Scanner(text);
        scn.useDelimiter(dot2Pattern);
        Abreviation abrv = new Abreviation();
        book(abrv,scn);
        return abrv;
    }
    
    private static void book(Abreviation abrv,Scanner scn) throws Exception{
        if(scn.hasNext(numberPattern)){
            String token = scn.next(numberPattern);
            abrv.setBook(token+" ");
        }
        simpleBookName(abrv, scn);
    }
    
    private static void simpleBookName(Abreviation abrv,Scanner scn) throws Exception{
        
        if(scn.hasNext(wordPattern)){
            String token = scn.next(wordPattern);
            if(abrv.getBook()!=null){
                abrv.setBook(abrv.getBook()+token);
            }else{
                abrv.setBook(token);
            }
        }else{
            throw new Exception("Invalid book name");
        }
        
        //Para los que tienen dos palabaras en el nombre
        if(scn.hasNext(wordPattern)){
            String token = scn.next(wordPattern);
            abrv.setBook(abrv.getBook()+token);
        }
        
        chapter(abrv,scn);
    }
    
    private static void chapter(Abreviation abrv,Scanner scn) throws Exception{
        if(scn.hasNext(numberPattern)){
            String token = scn.next(numberPattern);
            abrv.setChapter(token);
        }
        verse(abrv,scn);
    }
    
    private static void verse(Abreviation abrv,Scanner scn) throws Exception{
        if(scn.hasNext(numberPattern)){
            String token = scn.next(numberPattern);
            abrv.setVerse(token);
        }
    }
}
